<template>
  <div class="ccui-app-container">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <el-search
        ref="search"
        :formProp="formData"
        @search="search"
        :isShowSearch="isShowSearch"
        class="ccui-highsearch"
        :selectClear="true"
      >
        <div class="ccui-tab-wrapper">
          <el-button type="table-top-active" size="mini"
            >全部({{ totalNum }})</el-button
          >
        </div>
        <el-export-button
          class="export-button"
          @export-excel="exportExcel"
          @export-pdf="exportPdf"
          style="display: inline-block; position: absolute; right: 0; top: 0"
        ></el-export-button>
        <template slot="search">
          <el-input
            v-model="formData.contractName"
            clearable
            searchLabel="合同名称"
            placeholder="请输入合同名称模糊查询"
            @blur="handleTrim('contractName')"
          ></el-input>
          <el-input
            v-model="formData.partyBName"
            clearable
            searchLabel="供应商1"
            placeholder="请输入供应商1模糊查询"
            @blur="handleTrim('partyBName')"
          ></el-input>
          <el-input
            v-model="formData.contractCode"
            clearable
            searchLabel="合同编号"
            placeholder="请输入合同编号模糊查询"
            @blur="handleTrim('contractCode')"
          ></el-input>
          <el-input
            v-model="formData.partyBNameBak"
            clearable
            searchLabel="供应商2"
            placeholder="请输入供应商2模糊查询"
            @blur="handleTrim('partyBNameBak')"
          ></el-input>
          <el-input
            v-model="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位模糊查询"
            @blur="handleTrim('reportInOrgName')"
          ></el-input>
          <el-date-picker
            v-model="formData.compileDate"
            type="date"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            searchLabel="编制日期"
            placeholder="请选择编制日期查询"
            slot="searchItem6"
          >
          </el-date-picker>
          <el-date-picker
            v-model="formData.enabledDate"
            type="date"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            searchLabel="生效日期"
            placeholder="请选择生效日期查询"
            slot="searchItem8"
          >
          </el-date-picker>
          <el-date-picker
            v-model="formData.shenPiTongGuoDate"
            :clearable="true"
            searchLabel="审批通过日期"
            align="right"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
          <el-input
            v-model="formData.partyAName"
            clearable
            searchLabel="合同签订单位(甲方)"
            placeholder="请输入合同签订单位(甲方)模糊查询"
            @blur="handleTrim('partyAName')"
          ></el-input>
          <el-input
            v-model="formData.thirdCategoriesOfName"
            clearable
            searchLabel="分类名称"
            placeholder="请输入分类名称模糊查询"
            @blur="handleTrim('thirdCategoriesOfName')"
          ></el-input>
          <el-select
            v-model="formData.contractState"
            clearable
            placeholder="请选择合同状态查询"
            searchLabel="合同状态"
            @change="handleContractState"
          >
            <el-option key="1" label="审批通过" value="5"></el-option>
            <el-option key="2" label="已生效" value="9"></el-option>
            <el-option key="3" label="生效中" value="8"></el-option>
          </el-select>
        </template>
        <!-- 表单高级搜索 -->
        <el-input
          v-model="formData.contractName"
          clearable
          searchLabel="合同名称"
          placeholder="请输入合同名称模糊查询"
          slot="searchItem1"
          @blur="handleTrim('contractName')"
        ></el-input>
        <el-input
          v-model="formData.partyBName"
          clearable
          searchLabel="供应商1"
          placeholder="请输入供应商1模糊查询"
          slot="searchItem2"
          @blur="handleTrim('partyBName')"
        ></el-input>
        <el-input
          v-model="formData.contractCode"
          clearable
          searchLabel="合同编号"
          placeholder="请输入合同编号模糊查询"
          slot="searchItem3"
          @blur="handleTrim('contractCode')"
        ></el-input>
        <el-input
          v-model="formData.partyBNameBak"
          clearable
          searchLabel="供应商2"
          placeholder="请输入供应商2模糊查询"
          slot="searchItem5"
          @blur="handleTrim('partyBNameBak')"
        ></el-input>
        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位模糊查询"
          slot="searchItem6"
          @blur="handleTrim('reportInOrgName')"
        ></el-input>
        <el-date-picker
          v-model="formData.compileDate"
          type="date"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          searchLabel="编制日期"
          placeholder="请选择编制日期查询"
          slot="searchItem7"
        >
        </el-date-picker>
        <el-date-picker
          v-model="formData.enabledDate"
          type="date"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          searchLabel="生效日期"
          placeholder="请选择生效日期"
          slot="searchItem8"
        >
        </el-date-picker>
        <el-date-picker
          v-model="formData.shenPiTongGuoDate"
          :clearable="true"
          searchLabel="审批通过日期"
          align="right"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          slot="searchItem9"
        >
        </el-date-picker>
        <el-input
          v-model="formData.partyAName"
          clearable
          searchLabel="合同签订单位(甲方)"
          placeholder="请输入合同签订单位(甲方)模糊查询"
          slot="searchItem10"
          @blur="handleTrim('partyAName')"
        ></el-input>
        <el-input
          v-model="formData.thirdCategoriesOfName"
          clearable
          searchLabel="分类名称"
          placeholder="请输入分类名称模糊查询"
          slot="searchItem11"
          @blur="handleTrim('thirdCategoriesOfName')"
        ></el-input>
        <el-select
          v-model="formData.contractState"
          clearable
          placeholder="请选择合同状态查询"
          searchLabel="合同状态"
          @change="handleContractState"
          slot="searchItem12"
        >
          <el-option key="1" label="审批通过" value="5"></el-option>
          <el-option key="2" label="已生效" value="9"></el-option>
          <el-option key="3" label="生效中" value="8"></el-option>
        </el-select>
      </el-search>
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        v-if="tableHack"
        ref="multipleTable"
        :data="tableData"
        :fit="true"
        :row-style="rowClass"
        @cell-click="cellClick"
        :cell-style="cellStyle"
        border
        class="ccui-multifunctional-table"
        @selection-change="handleSelectionChange"
        @header-dragend="tableTitleWidth"
        :min-height="9999"
      >
        <template v-for="(table, index) in tableTheadOptions">
          <el-table-column
            v-if="table.checked"
            :fixed="table.fixed || false"
            :type="table.type"
            :key="index"
            :label="table.label"
            :min-width="table.width"
            :prop="table.prop"
            :filters="table.filters"
            :align="table.align"
            :header-align="table.headerAlign || 'left'"
            :show-overflow-tooltip="true"
          ></el-table-column>
        </template>
      </el-table>
      <div class="ccui-table-footer" v-if="totalNum > 0">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="getLocalPageSize()"
            :current-page="formDataSearch.pageNo"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @prev-click="handlePrev"
            @next-click="handleNext"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            class="ccui-pagination-btn"
            size="mini"
            type="default"
            @click="handleChangeSize('none')"
            >确定</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getParameterList } from "../api";
import { setSessionItem, getSessionItem, ishasAgentId } from "@/basa/utils";
import { getDetail, detailExport } from "@/basa/api";
import { exportData } from "@/basa/utils/public";
export default {
  name: "contractParameterList",
  data() {
    return {
      orgId: null, //orgId
      //多页签
      focuses: [
        { focus: "Submit" },
        { focus: "Approval" },
        { focus: "ApprovalTurn" }
      ],
      workStatus: "",
      // 表格数据
      tableData: [],
      tableHack: true,
      // 表格命名
      tableName: this.tableList.contractParameterList,
      // 表格数据
      tableThead: [],
      // 锁定表格
      fixedTableThead: [
        {
          label: "序号",
          prop: "id",
          width: "38",
          checked: true,
          fixed: true,
          type: "index"
        },
        {
          label: "合同编号",
          prop: "contractCode",
          width: "130",
          checked: true,
          fixed: true,
          align: "left"
        }
      ],
      // 非锁定表格
      unfixedTableThead: [
        {
          label: "合同正式编号",
          prop: "formalContractCode",
          width: "130",
          checked: true,
          align: "left"
        },
        {
          label: "合同名称",
          prop: "contractName",
          width: "300",
          checked: true,
          align: "left"
        },
        {
          label: "供应商1",
          prop: "partyBName",
          width: "200",
          checked: true,
          align: "left"
        },
        {
          label: "供应商2",
          prop: "partyBNameBak",
          width: "200",
          checked: true,
          align: "left"
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "200",
          checked: true,
          align: "left"
        },
        {
          label: "合同签订单位(甲方)",
          prop: "partyAName",
          width: "200",
          checked: true,
          align: "left"
        },
        {
          label: "合同数量",
          prop: "contractNum",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "合同金额(含税)",
          prop: "initTotalContractPriceIncludeTax",
          width: "140",
          checked: true,
          align: "right"
        },
        {
          label: "分类名称",
          prop: "thirdCategoriesOfName",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "编制日期",
          prop: "compileDate",
          width: "100",
          checked: true,
          align: "left"
        },

        {
          label: "生效日期",
          prop: "enabledDate",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "审批通过日期",
          prop: "checkDate",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "合同状态",
          prop: "contractState",
          width: "70",
          checked: true,
          align: "left"
        },
        {
          label: "编制人",
          prop: "compileUser",
          width: "60",
          checked: true,
          align: "left"
        }
      ],
      //全部数量
      totalNum: 1,
      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      popoverShow: false,
      selectRow: [],
      selectData: [],
      // 高级搜索数据 start
      // 高级搜索提交数据
      isShowSearch: true,
      formData: {
        reportOrgId: getSessionItem("userInfo", "orgId"),
        contractName: "",
        contractCode: "",
        partyBName: "",
        partyBNameBak: "",
        compileDate: "",
        checkDate: "",
        enabledDate: "",
        partyAName: "",
        thirdCategoriesOfName: "",
        contractState: "",
        shenPiTongGuoDate: [],
        pageNo: 1,
        pageSize: this.getLocalPageSize(),
        // reportOrgId: null,
        isShowPageLoading: true
      },
      formDataSearch: {
        reportOrgId: getSessionItem("userInfo", "orgId"),
        contractName: "",
        contractCode: "",
        partyBName: "",
        partyBNameBak: "",
        compileDate: "",
        checkDate: "",
        enabledDate: "",
        partyAName: "",
        thirdCategoriesOfName: "",
        contractState: "",
        pageNo: 1,
        pageSize: this.getLocalPageSize(),
        // reportOrgId: null,
        isShowPageLoading: true
      }
      // 高级搜索数据 end
    };
  },
  activated() {
    // this.getDetail();
    this.$refs.search.resetForm();
    this.search(this.formData);
  },

  mounted() {
    this.initData();
    this.getDetail();
  },
  methods: {
    //去空格
    handleTrim(key) {
      this.$set(
        this.formData,
        key,
        this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    },
    getDetail() {
      getDetail({}).then(res => {
        if (res.data.code == 0) {
          this.orgId = res.data.data.orgId;
          this.formData.reportOrgId = res.data.data.orgId;
          this.formDataSearch.reportOrgId = res.data.data.orgId;
          this.getParameterList(this.formData); //请求列表
        }
      });
    },
    initData() {
      this.setTableWidth();
      this.renderTable();
    },
    //合同状态
    handleContractState(data) {
      if (data) {
        this.formData.contractState = data;
      }
    },

    //查列表
    getParameterList(data) {
      getParameterList(data).then(res => {
        if (res.data.code == 0) {
          this.tableData = res.data.data.rows;
          this.tableData.forEach((item, index) => {
            index = 1 + index;
            item.contractState =
              item.contractState == 5
                ? "审批通过"
                : item.contractState == 8
                ? "生效中"
                : item.contractState == 9
                ? "已生效"
                : "";
            if (item.compileDate) {
              item.compileDate = item.compileDate.substring(0, 10);
            }
            if (item.checkDate) {
              item.checkDate = item.checkDate.substring(0, 10);
            }
            if (item.enabledDate) {
              item.enabledDate = item.enabledDate.substring(0, 10);
            }
            if (
              item.initTotalContractPriceIncludeTax ||
              item.initTotalContractPriceIncludeTax === 0
            ) {
              item.initTotalContractPriceIncludeTax = Number(
                item.initTotalContractPriceIncludeTax
              ).toFixed(2);
            }
            if (item.contractNum || item.contractNum === 0) {
              item.contractNum = Number(item.contractNum).toFixed(3);
            }
          });
          this.totalNum = res.data.data.recordsTotal;
        }
      });
    },
    // 根据返回状态显示不同的文字颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "transparent" };
      }
      if (columnIndex == 1) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    },
    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = this.fixedTableThead.concat(
        this.unfixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          localTableData.forEach(item => {
            let index = this.unfixedTableThead.findIndex(
              cItem => item.prop === cItem.prop
            );
            index !== -1 &&
              (this.unfixedTableThead[index].checked = item.checked);
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.fixedTableThead.concat(this.unfixedTableThead);
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.fixedTableThead.concat(this.unfixedTableThead);
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.tableHack = false;
      this.$nextTick(() => {
        this.tableHack = true;
      });
    },
    handleSelectionChange(data) {
      this.selectData = data;
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },
    // 查看
    cellClick(row, column, columnIndex) {
      if (column.label === "合同编号") {
        this.$router.push({
          path: "/contractManagement/contractAgreement/item-detail",
          query: { concId: row.id, type: "account" }
        });
      }
    },
    // 分页
    // 上一页
    handlePrev() {},
    // 下一页
    handleNext() {},
    //  显示条数更改
    handleSizeChange(val) {
      this.formDataSearch.pageNo = 1;
      this.formDataSearch.pageSize = val;
      setSessionItem("pageSize", this.tableName, val);
      this.getParameterList(this.formDataSearch);
    },
    //翻页确定
    handleChangeSize() {
      this.getParameterList(this.formDataSearch);
    },
    // 获取默认条数
    getLocalPageSize() {
      return (
        getSessionItem("pageSize", this.tableList.contractParameterList) || 10
      );
    },
    // 当前页码更改
    handleCurrentChange(val) {
      // 跳转翻页都会调这个方法
      this.formDataSearch.pageNo = val;
      this.getParameterList(this.formDataSearch);
    },
    // 分页 end
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      this.formDataSearch = JSON.parse(JSON.stringify(searchData));
      if (this.formDataSearch.shenPiTongGuoDate) {
        this.formDataSearch.qryBeginCheckDate =
          this.formDataSearch.shenPiTongGuoDate[0];
        this.formDataSearch.qryEndCheckDate =
          this.formDataSearch.shenPiTongGuoDate[1];
      }
      this.formDataSearch.reportOrgId = getSessionItem("userInfo", "orgId");
      this.formDataSearch.pageNo = 1;
      this.formDataSearch.isShowPageLoading = true;
      this.formDataSearch.pageSize = this.getLocalPageSize();
      this.getParameterList(this.formDataSearch);
    },
    // 高级搜索 end
    //导出全部
    exportPdf() {
      let formDataSearch = JSON.parse(JSON.stringify(this.formDataSearch));
      formDataSearch.pageNo = 1;
      formDataSearch.pageSize = 3000;
      delete formDataSearch.isShowPageLoading;
      detailExport({
        ...formDataSearch,
        type: "smppcconc/accountExport"
      }).then(res => {
        exportData(res);
      });
    },
    //导出当前
    exportExcel() {
      let formDataSearch = JSON.parse(JSON.stringify(this.formDataSearch));
      delete formDataSearch.isShowPageLoading;
      detailExport({
        ...formDataSearch,
        type: "smppcconc/accountExport"
      }).then(res => {
        exportData(res);
      });
    }
  },

  beforeRouteLeave(to, from, next) {
    for (var key in this.$vnode.parent.parent.componentInstance.cache) {
      delete this.$vnode.parent.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    next();
  }
};
</script>
<style lang="scss" scoped>
/deep/.ccui-advanced-search-wrapper
  .el-search
  .el-searchs-bottom
  .el-form-item
  .el-form-item__label {
  min-width: 126px !important;
}
/deep/ #ccui-paging .ccui-pagination-btn {
  display: block;
}
/deep/ .el-search .el-searchs-box {
  margin-right: 70px;
}
/deep/ .el-searchs-box {
  width: 405px !important;
}
// /deep/ .el-range-input {
//   width: 75px !important;
// }
/deep/
  .ccui-advanced-search-wrapper
  .el-search
  .ccui-search-wrapper
  .el-searchs
  .el-searchs-right
  .el-date-editor {
  padding-right: 0px !important;
}
</style>
